var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var log4js = require('log4js');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
let session = require('express-session');   // 使用session模块


var index = require('./routes/index');

var users = require('./routes/users');
var ueditor = require('./utils/ueditor/index');
var blog = require('./routes/blog.js');

var billRoute = require('./routes/consume/billRoutes');

var ssqRoute = require('./routes/ssq/index');


var app = express();


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /res
//app.use(favicon(path.join(__dirname, 'res', 'favicon.ico')));
// app.use(logger(':remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :response-time ms :res[content-length] ":referrer" ":user-agent"'));
app.use(logger('dev'));
// app.use(log4js.connectLogger(log4js.getLogger("http"), { level: 'trace' }));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use('/res', express.static(path.join(__dirname, 'res')));

app.use(session({
  secret: 'secret',
  // 这里的name值得是cookie的name，默认cookie的name是：connect.sid
  name: 'sid',
  'resave': false,
  saveUninitialized: true,
  cookie: {
    maxAge: 30 * 60 * 1000
  }
}));
app.use(function (req, res, next) {
  var views = req.session.views
  if (!views) {
    views = req.session.views = {}
  }
  // get the url pathname
  var pathname = req.url;
  // count the views
  views[pathname] = (views[pathname] || 0) + 1;
  next();
});

app.use('/', index);

app.use('/users', users);
app.use('/ueditor', ueditor);
app.use('/api/blog', blog);
app.use('/consume/bill', billRoute);
app.use('/api/ssq', ssqRoute);


// catch 404 and forward to error handler
app.use(function (req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
